package dch.util;

import dch.entity.Page;


public class PageUtil {

	public static Page createPage(Page page, long totalRecords) {
		return createPage(page.getPageSize(), page.getCurrentPage(),totalRecords);
	}
	
	public static Page createPage(int pageSize, int currentPage,long totalRecords) {
		
		pageSize = getPageSize(pageSize);
		int totalPage = getTotalPage(pageSize, totalRecords);
		currentPage = getCurrentPage(currentPage,totalPage);
		if(currentPage<0){
			currentPage=0;
		}else if(currentPage>totalPage){
			currentPage=totalPage;
		}
		int beginIndex = getBeginIndex(pageSize, currentPage);
		
		boolean hasNextPage = hasNextPage(currentPage, totalPage);
		boolean hasPrePage = hasPrePage(currentPage);
		
		return new Page(hasPrePage, hasNextPage, pageSize, totalPage,
		currentPage, beginIndex, totalRecords);
	}
	
	private static int getPageSize(int pageSize) {
		return pageSize == 0 ? 10 : pageSize;
	}
	
	private static int getCurrentPage(int currentPage,int totalPage) {
		if(currentPage<1){
			return 1;
		}else if(currentPage>totalPage){
			return totalPage;
		}else{
			return currentPage;
		}
	}
	
	private static int getBeginIndex(int pageSize, int currentPage) {
		return (currentPage - 1) * pageSize;
	}
	
	private static int getTotalPage(int pageSize, long totalRecords) {
		int totalPage = 0;
		
		if (totalRecords % pageSize == 0)
			totalPage = (int) (totalRecords / pageSize);
		else
			totalPage = (int) (totalRecords / pageSize + 1);
		
		return totalPage;
	}
	
	private static boolean hasPrePage(int currentPage) {
		return currentPage == 1 ?false:true;
	}
	
	private static boolean hasNextPage(int currentPage, int totalPage) {
		return currentPage == totalPage || totalPage == 0 ? false : true;
	}

}
